package com.zsd.android.common

import com.zsd.android.common.retrofit.BaseFunc
import com.zsd.android.common.retrofit.BaseSubscribe
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

open class BaseModel<T>(clazz: Class<T>) {

    //单例，创建Retrofit和Api接口的
    protected val modelFactory: ModelFactory
    //Api接口，组件化使用：AppApi, LoginApi等
    protected val api: T

    init {
        modelFactory = ModelFactory.getInstance()!!
        //利用Class，通过Retrofit创建Api接口
        api = modelFactory.createApi(clazz)
    }

    open fun <T> doSubscribe(observable: Observable<T>, subscribe: BaseSubscribe<T>) {
        observable
            .compose { upstream: Observable<T> ->
                upstream.subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .onErrorResumeNext(BaseFunc<T>())
                    .observeOn(AndroidSchedulers.mainThread())
            }
            .subscribe(subscribe)
    }
}